package com.dragonfly.shutter.controllers;

import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.dragonfly.shutter.DAOIbatisImpls.AlbumDAOIbatisImpl;
import com.dragonfly.shutter.DAOIbatisImpls.PictureAlbumDAOIbatisImpl;
import com.dragonfly.shutter.DAOIbatisImpls.PictureDAOIbatisImpl;
import com.dragonfly.shutter.DAOs.AlbumDAO;
import com.dragonfly.shutter.DAOs.PictureAlbumDAO;
import com.dragonfly.shutter.DAOs.PictureDAO;
import com.dragonfly.shutter.DAOs.TagDAO;
import com.dragonfly.shutter.beans.Album;
import com.dragonfly.shutter.beans.PictureAlbum;
import com.dragonfly.shutter.beans.PictureDetail;



/**
 * 处理删除相册的控制器
 * @author 王长乐
 *
 */

@Controller
@RequestMapping("/deleteAlbum.html")
@SessionAttributes("userID")
public class DelAlbumController {
	@Autowired
	private AlbumDAO albumDAO;     //相册DAO
	@Autowired
	private PictureDAO pictureDAO;  //相片DAO
	@Autowired
	private PictureAlbumDAO pictureAlbumDAO;  //相片相册对应DAO
	@Autowired
	private TagDAO tagDAO;


	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView deleteAlbumProcess(ModelMap model,
			@ModelAttribute("userID") Integer userID,
			@RequestParam(value = "deleteAlbumID", required = false)String deleteAlbumID
			
			)
	{
		if(userID==null)
		{
			return new ModelAndView("redirect:/login.html");
		}
		else
		{
			
		if( deleteAlbumID== null||"".equals(deleteAlbumID.trim()) ){
			
			return new ModelAndView("redirect:/album.html?albumID="+deleteAlbumID);
			
		}
		else{
			    Album album=new Album();
			    
			    album.setAlbumID(Integer.parseInt(deleteAlbumID));
			  
				if(albumDAO.selectAlbumByID(album.getAlbumID())!=null)
				{
					deleteAlbum(album);
				}
			
			return new ModelAndView("redirect:/user.html");
		}
		}
	}
	
	/**
	 * 删除所选相册
	 * @param album 想要删除的相册对象
	 */
	private void deleteAlbum(Album album)
	{
		
		albumDAO.deleteAlbumByID(album);
		tagDAO.deleteAlbumTagByAlbumId(album.getAlbumID());
		List<PictureAlbum> PictureAlbumList=pictureAlbumDAO.selectPictureAlubmByAlbumID(album.getAlbumID());
		Iterator<PictureAlbum> iter=PictureAlbumList.iterator();
		while(iter.hasNext())
		{
			
			PictureAlbum pictureAlbum = (PictureAlbum) iter.next();
			pictureAlbumDAO.deletePictureAlbumByID(pictureAlbum);
			PictureDetail pictureDetail=new PictureDetail();
			pictureDetail.setPictureID(pictureAlbum.getPictureBrief().getPictureID());
			pictureDAO.updatePictureDelFlag(pictureDetail);
		}
		
		
	}
}	
	
